package com.xuecheng.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /*用户登录的业务逻辑
    参数：手机号，密码，类型
    返回值：jwt token字符串  (用户id，机构id，机构的名称)  这是token中设置的数据
          用户名
    */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.获取手机号，密码，类型
        String phone = dto.getUsername();
        String password = dto.getPassword();
        String utype = dto.getUtype();
        //2.对参数进行非空校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password) || StringUtils.isEmpty(utype)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //3.根据手机号码和类型查询用户
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        qw.eq(User::getUtype,utype);
        User user = this.getOne(qw);
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //4.比较输入的密码和数据库中的密码是否一直
        password = DigestUtil.md5Hex(password);  //加密
        if (!password.equals(user.getPassword())) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //5.生成token
        Map map = new HashMap();
        map.put("userId",user.getId());
        map.put("companyId",user.getCompanyId());
        map.put("companyName",user.getCompanyName());
        String token = JwtUtils.createToken(map, 240);
        //6.构造返回值
        LoginVo vo = new LoginVo();
        vo.setAccess_token(token);
        vo.setUsername(user.getName());
        return ResponseResult.okResult(vo);
    }
}
